package sql
{
	import flash.data.SQLConnection;
	import flash.data.SQLMode;
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	import flash.filesystem.File;

	public class SqlManager
	{
		private static var _ins:SqlManager;
		
		private var _conn:SQLConnection;
		private var _state:SQLStatement;
		
		public function SqlManager()
		{
		}
		
		public static function get instance():SqlManager
		{
			if( _ins==null ) _ins = new SqlManager();
			return _ins;
		}
		
		private function init( db:String ):void
		{
			_conn = new SQLConnection();
			_conn.addEventListener( SQLEvent.OPEN, onSqlOpen );
			_conn.addEventListener( SQLErrorEvent.ERROR, onError );
			
			_state = new SQLStatement();
			_state.sqlConnection = _conn;
		}
		
		public function connect( db:String ):void
		{
			var file:File = new File( db );
			_conn.open( file, SQLMode.CREATE );
		}
		
		public function query( sql:String ):SQLResult
		{
			if( !_conn.connected )
			{
				throw new Error("请先连接数据库");
			}
			_state.text = sql;
			_state.execute();
			
			return _state.getResult();
		}
		
		private function onError( e:SQLErrorEvent ):void
		{
			trace( "error" );
		}
		
		private function onSqlOpen( e:SQLEvent ):void
		{
			trace( "open" );
		}
	}
}